package com.zhuoya.healthcard.net;

import com.blankj.utilcode.util.LogUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * @Author: glg
 * 接口重试
 */
public class RetryWithDelay implements Function<Observable<Throwable>, ObservableSource<?>> {

    /**
     * 最大重试次数
     */
    private final int maxRetries;

    /**
     * 重试间隔
     */
    private final int retryDelayMillis;

    /**
     * 累计重试次数
     */
    private int retryCount;


    public RetryWithDelay(int maxRetries, int retryDelayMillis) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
    }

    @Override
    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) {

        return throwableObservable.flatMap((Function<Throwable, ObservableSource<?>>) throwable -> {
            if (++retryCount <= maxRetries) {
                // When this Observable calls onNext, the original Observable will be retried .
                LogUtils.e("get error, it will try after " + retryDelayMillis
                        + " millisecond, retry count " + retryCount);
                return Observable.timer(retryDelayMillis,
                        TimeUnit.MILLISECONDS);
            }
            // Max retries hit. Just pass the error along.
            return Observable.error(throwable);
        });





    }
}

